"""
认证相关路由
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from pydantic import BaseModel, EmailStr

from backend.app.db.database import get_db
from backend.app.db.operations import verification
from backend.app.utils.email import send_verification_email

router = APIRouter(prefix="/auth", tags=["认证"])

class EmailRequest(BaseModel):
    """邮箱请求模型"""
    email: EmailStr

class VerificationRequest(BaseModel):
    """验证码请求模型"""
    email: EmailStr
    code: str

@router.post("/send-code")
async def send_verification_code(
    request: EmailRequest,
    db: Session = Depends(get_db)
):
    """
    发送验证码
    """
    # 创建验证码
    verification_code = verification.create_verification_code(db, request.email)
    
    # 发送验证码邮件
    await send_verification_email(request.email, verification_code.code)
    
    return {"message": "验证码已发送"}

@router.post("/verify")
async def verify_email_code(
    request: VerificationRequest,
    db: Session = Depends(get_db)
):
    """
    验证邮箱验证码
    """
    if verification.verify_code(db, request.email, request.code):
        return {
            "message": "验证成功",
            "email": request.email
        }
    raise HTTPException(
        status_code=status.HTTP_400_BAD_REQUEST,
        detail="验证码无效或已过期"
    ) 